import React, {useEffect, useState} from 'react';
import {
    Avatar,
    Button,
    List,
    Table,
    Tooltip,
    Rate,
    Form,
    Input,
    Flex,
    Select,
    InputNumber,
    Modal,
    Row,
    Col, Tag, message, Popconfirm, Radio, Space, Divider, Menu, Dropdown, Descriptions, Image
} from 'antd';
import http from '../services/http'
import WorkDetail from "./components/WorkDetail";
import {useRouter} from "next/router";
import {PlusOutlined} from "@ant-design/icons";

export default function DeptPage() {
    // 意思是前端点击应聘后，状态变成待回复或者不合适，后续我将会设计一个next.js构建的websocket去进行实时的hr和应聘人员对话，只要hr回复了一条消息，则状态马上久变成沟通中，这个沟通中就是待审核的意思，所以待审核去掉，当hr发出面试邀请，则状态变成待面试，应聘者可以在前端点击放弃面试，或者接受面试，这个后续会做一个线上面试的视频通话或者语音通话，面试结束后，状态有两中，一种是面试失败，一种是待入职，然后应聘人员可以点击接受入职，或者放弃入职，
    // 已应聘：应聘者提交申请后的初始状态。
    // 不合适：初筛后发现应聘者不符合要求。
    // 待回复：HR 查看应聘申请并给予反馈后的状态，等待应聘者响应。
    // 沟通中：HR 与应聘者进行实时对话后的状态。
    // 待面试：HR 发出面试邀请后的状态。
    // 放弃面试：应聘者选择不参加面试。
    // 面试失败：面试后，应聘者未能通过面试。
    // 待入职：面试通过后，应聘者准备入职的状态。
    // 已入职：完成所有入职手续后的状态。
    // 放弃入职：应聘者在入职前决定放弃

    const [seekerOneDetail, setSeekerOneDetail] = useState(false)
    const [seekerDetailInfo, setSeekerDetailInfo] = useState({})
    const closeSeekerOneDetail = () => {
        setSeekerOneDetail(false)
    }
    const SeekerOneDetailItems = [
        {
            key: '1',
            label: '头像',
            children: <Image src={seekerDetailInfo.avatar} width={50} height={50}/>
        },
        {
            key: '2',
            label: '用户名',
            children: <span>{seekerDetailInfo.username}</span>
        },
        {
            key: '3',
            label: '昵称',
            children: <span>{seekerDetailInfo.nickname}</span>
        },
        {
            key: '4',
            label: '邮箱',
            children: <span>{seekerDetailInfo.email}</span>
        },
        {
            key: '5',
            label: '常驻职位',
            children: <span>{seekerDetailInfo.work_position}</span>
        },
        {
            key: '6',
            label: '工作年限',
            children: <span>{seekerDetailInfo.year}</span>
        },
    ]

    const handleAction = (seeker, action) => {
        console.log('seeker', seeker)//这个是该人员的信息，比如nickname,avatar
        console.log('action', action)
        if (action) {
            if (action === 'view_details') {
                setSeekerDetailInfo(seeker)
                setSeekerOneDetail(true)
            } else if (action === 'contact') {
                //这里的contactRole为worker,代表现在是去联系应聘者
                router.push({
                    pathname: '/chat_box',
                    query: {userId: seeker.id, contactRole: 'worker',workId:seeker.workId}
                });
            }
            //标记不合适
            else if (action === 'inappropriate') {
                const data = {
                    workId: seeker.workId,
                    userId: seeker.id,
                    status: 2
                }
                http.put('/work/updateWorkSeeker', data).then((res) => {

                    const data2 = {
                        workId: seeker.workId
                    }
                    http.post('/work/getSeekers', data2).then((res) => {
                        res.data.forEach(seek => {
                            seek.workId = seeker.workId;
                        });
                        setSeekersDetailData(res.data);
                        message.success('该人员已标记为不合适')
                    }).catch((error) => {
                        message.error(error)
                    })

                }).catch((error) => {
                    message.error(error)
                })
            } else if (action === 'schedule_interview') {
                const data = {
                    workId: seeker.workId,
                    userId: seeker.id,
                    status: 4
                }
                http.put('/work/updateWorkSeeker', data).then((res) => {
                    const data2 = {
                        workId: seeker.workId
                    }
                    http.post('/work/getSeekers', data2).then((res) => {
                        res.data.forEach(seek => {
                            seek.workId = seeker.workId;
                        });
                        setSeekersDetailData(res.data);
                        message.success('已安排面试！')
                    }).catch((error) => {
                        message.error(error)
                    })

                }).catch((error) => {
                    message.error(error)
                })
            } else if (action === 'complete_interview') {
                const data = {
                    workId: seeker.workId,
                    userId: seeker.id,
                    status: 7
                }
                http.put('/work/updateWorkSeeker', data).then((res) => {
                    const data2 = {
                        workId: seeker.workId
                    }
                    http.post('/work/getSeekers', data2).then((res) => {
                        res.data.forEach(seek => {
                            seek.workId = seeker.workId;
                        });
                        setSeekersDetailData(res.data);
                        message.success('已标记面试成功！')
                    }).catch((error) => {
                        message.error(error)
                    })

                }).catch((error) => {
                    message.error(error)
                })
            } else if (action === 'fail_interview') {
                const data = {
                    workId: seeker.workId,
                    userId: seeker.id,
                    status: 6
                }
                http.put('/work/updateWorkSeeker', data).then((res) => {
                    const data2 = {
                        workId: seeker.workId
                    }
                    http.post('/work/getSeekers', data2).then((res) => {
                        res.data.forEach(seek => {
                            seek.workId = seeker.workId;
                        });
                        setSeekersDetailData(res.data);
                        message.success('已标记面试失败！')
                    }).catch((error) => {
                        message.error(error)
                    })

                }).catch((error) => {
                    message.error(error)
                })
            }
        }
    };

    const cancelInterview = (record, code) => {
        const data = {
            workId: record.id,
            userId: userInfo.id,
            status: code
        }
        http.put('/work/updateWorkSeeker', data).then((res) => {
            message.success('取消成功！')
            getDataList();
        }).catch((error) => {
            message.error(error)
        })

    }

    const acceptOffer = (record) => {
        const data = {
            workId: record.id,
            userId: userInfo.id,
            status: 8
        }
        http.put('/work/updateWorkSeeker', data).then((res) => {
            message.success('入职成功！')
            getDataList();
        }).catch((error) => {
            message.error(error)
        })

    }

    //针对hr和管理员的
    const renderActions = (seeker) => {
        const actions = [];
        switch (seeker.status) {
            case 1: // 已应聘（可以联系，或者标记不合适）
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Button key="contact" onClick={() => handleAction(seeker, 'contact')}
                            type="primary" size="small">去联系</Button>,
                    <Popconfirm
                        title={`此操作不可逆，确定标记不合适吗?`}
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => handleAction(seeker, 'inappropriate')}>
                        <Button key="inappropriate" type="primary"
                                danger size="small">标记不合适</Button>
                    </Popconfirm>,
                    <Button key="schedule_interview" onClick={() => handleAction(seeker, 'schedule_interview')}
                            className="bg-teal-500 text-amber-50" size="small">安排面试</Button>
                );
                break;
            case 2: // 不合适（也可以查看详情）
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Tag color="#f50">已标记不合适</Tag>,
                );
                break;
            case 3: // 沟通中（可以联系，或者安排面试或者标记不合适）
                actions.push(
                    <Button key="contact" onClick={() => handleAction(seeker, 'contact')}
                            type="primary" size="small">去联系</Button>,
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Popconfirm
                        title={`此操作不可逆，确定标记不合适吗?`}
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => handleAction(seeker, 'inappropriate')}>
                        <Button key="inappropriate" type="primary"
                                danger size="small">标记不合适</Button>
                    </Popconfirm>,
                    <Button key="schedule_interview" onClick={() => handleAction(seeker, 'schedule_interview')}
                            className="bg-teal-500 text-amber-50" size="small">安排面试</Button>
                );
                break;
            case 4: // 待面试（面试通过安排入职，或者面试失败，不通过）
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Popconfirm
                        title={`此操作不可逆，确定面试通过吗?`}
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => handleAction(seeker, 'complete_interview')}>
                        <Button key="complete_interview" type="primary" size="small">面试通过</Button>
                    </Popconfirm>,
                    <Popconfirm
                        title={`此操作不可逆，确定不通过面试吗?`}
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => handleAction(seeker, 'fail_interview')}>
                        <Button key="fail_interview" type="primary" danger size="small">面试失败</Button>
                    </Popconfirm>
                );
                break;
            case 5: // 放弃面试了
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Tag color="#f50">已放弃面试</Tag>,
                );
                break;
            case 6: // 面试失败了
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Tag color="#f50">面试失败</Tag>,
                );
                break;
            case 7: //  面试通过了，发offer
                actions.push(
                    <Button key="contact" onClick={() => handleAction(seeker, 'contact')}
                            type="primary" size="small">去联系</Button>,
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Tag color="#2db7f5">待入职</Tag>,
                );
                break;
            case 8: //  该人员已入职
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Tag color="green">已入职</Tag>,
                );
                break;
            case 9: //  该人员已放弃入职
                actions.push(
                    <Button key="view" size="small"
                            onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>,
                    <Tag color="#f50">已放弃入职</Tag>
                );
                break;
            default:
                actions.push(
                    <Button key="view" onClick={() => handleAction(seeker, 'view_details')}>查看详情</Button>
                );
        }
        return actions;
    };

    const router = useRouter();
    const {TextArea} = Input;
    const {Option} = Select;
    //岗位相关统计数量
    const [workCounts, setWorkCounts] = useState({
        totalJobs: null,
        totalApplicants: null,
        averageSalary: null
    });

    const [userInfo, setUserInfo] = useState(null)

    //发布岗位的表单数据
    const [workForm] = Form.useForm();

    //是否显示自定义输入框
    const [customInput, setCustomInput] = useState(false);

    //福利待遇下拉框数据
    const benefitOptions = [
        {label: '五险一金', value: '五险一金'},
        {label: '股票期权', value: '股票期权'},
        {label: '弹性工作', value: '弹性工作'},
        {label: '年终奖金', value: '年终奖金'},
        {label: '带薪休假', value: '带薪休假'},
        {label: '绩效奖金', value: '绩效奖金'}
    ];

    //福利待遇下拉变化
    const benefitChange = (list) => {
        console.log('123', list)
    }

    //薪资变化调节值
    const handleSalaryChange = value => {
        console.log(value)
        // 当选择 "自定义" 时，显示输入框
        if (value === 'custom') {
            setCustomInput(true);
            workForm.setFieldsValue({
                min_salary: undefined,
                max_salary: undefined,
                salary_unit: undefined
            });
        } else {
            setCustomInput(false);
            const parts = value.split('/');
            if (parts.length > 1) {
                const range = parts[0].split('-');
                const unit = parts[1].trim();
                workForm.setFieldsValue({
                    min_salary: Number(range[0].trim()),
                    max_salary: Number(range[1].trim()),
                    salary_unit: unit
                });
            }
        }
    };

    //发布岗位
    const publishWork = () => {
        workForm.validateFields()
            .then(async (values) => {
                setPublishModalVisible(false)
                if (values.salary === 'custom') {
                    workForm.setFieldsValue({
                        salary: values.min_salary + '-' + values.max_salary + '/' + values.salary_unit
                    })
                }
                const workData = workForm.getFieldValue();
                const workData2 = {
                    ...workData,
                    userId: userInfo.id
                }
                http.post('/work/publishWork', workData2).then((res) => {
                    message.success('发布成功,请耐心等待审核')
                    getDataList();
                }).catch((error) => {
                    message.error(error)
                })
            }).catch((error) => {
            message.error(error)
        })
    }

    //删除岗位
    const handleDeleteWork = (workId) => {
        http.delete(`/work/${workId}`).then((res) => {
            message.success('删除成功!')
            getDataList();
        }).catch((error) => {
            message.error(error)
        })
    }

    //发布岗位的弹窗
    const [publishModalVisible, setPublishModalVisible] = useState(false);

    //岗位详情弹窗
    const [workDetailVisible, setWorkDetailVisible] = useState(false);
    //入职人员列表弹窗
    const [seekersDetailVisible, setSeekersDetailVisible] = useState(false);
    //岗位详情的数据
    const [workDetailData, setWorkDetailData] = useState(null)
    //入职人员详情的数据
    const [seekersDetailData, setSeekersDetailData] = useState(null)
    //关闭岗位详情弹窗
    const closeWorkDetail = () => {
        setWorkDetailVisible(false)
        setWorkDetailData(null)
    }

    //打开岗位详情弹窗
    const showWorkDetails = (record) => {
        setWorkDetailData(record);
        setWorkDetailVisible(true);
    };

    //关闭入职人员详情弹窗
    const closeWorkSeekerDetail = () => {
        setSeekersDetailVisible(false);
        setSeekersDetailData(null)
    }

    //打开入职人员详情弹窗
    const showWorkSeekerDetail = (record) => {
        const data = {
            workId: record.id
        }
        http.post('/work/getSeekers', data).then((res) => {
            res.data.forEach(seek => {
                seek.workId = record.id;
            });
            setSeekersDetailData(res.data);

            console.log('22312312', res.data)
            setSeekersDetailVisible(true);
        }).catch((error) => {
            if (error === 'Token已过期' || error === '无效的Token') {
                logout();
                message.error(error)
            } else {
                message.error(error)
            }
        })

    };

    //应聘操作
    const applyWork = (record) => {
        const data = {
            workId: record.id,
            userId: userInfo.id
        }
        http.post('/work/applyWorkSeeker', data).then((res) => {
            message.success('应聘成功！')
            getDataList();
        }).catch((error) => {
            message.error(error)
        })
    }

    const TableTitle = ({onAddClick}) => (
        <div className="flex justify-between items-center">
            <h2>岗位列表</h2>
            <Button type="primary" onClick={onAddClick}>发布岗位</Button>
        </div>
    );

    //点击发布岗位弹窗
    const handleAddClick = () => {
        console.log('点击了发布岗位');
        setPublishModalVisible(true)
    };

    const [workList, setWorkList] = useState([]);

    const [Role, setRole] = useState(null);

    //审核岗位
    const confirmWork = (workId) => {
        const data = {
            userId: userInfo.id,
            workId: workId,
            status: confirmStatus
        }
        http.put('/work/confirmWork', data).then((res) => {
            message.success('审核成功！')
            getDataList();
        }).catch((error) => {
            message.error(error)
        })
    }

    const handleRemoveWork = (id) => {
        console.log('123122')
        http.put(`/work/${id}`).then((res) => {
            message.success('下架成功！')
            getDataList();
        }).catch((error) => {
            message.error(error)
        })
    }

    //审核气泡选择值变化
    const selectConfirmStatus = (e) => {
        console.log('12312', e.target.value)
        setConfirmStatus(e.target.value)
    }

    const [confirmStatus, setConfirmStatus] = useState(1)


    const buttonWidth = 62;
    const gapWidth = 16;
    const calculateWidth = (role) => {
        let buttonCount;
        switch (role) {
            case 1:
            case 2:
                buttonCount = 5; //管理员有最多5个按钮
                break;
            case 3:
                buttonCount = 4;
                break;
            default:
                buttonCount = 2;
        }
        return buttonCount * buttonWidth + (buttonCount - 1) * gapWidth;
    }

    //动态设置宽度,针对操作列的宽度
    const dynamicWidth = calculateWidth(Role);

    const contactToHr = (record) => {
        console.log('22222', record)
        router.push({
            pathname: '/chat_box',
            query: {userId: record.user_id, contactRole: 'hr',workId:record.id}
        });
    }

    const columns = [{
        align: 'center',
        title: '岗位名称',
        dataIndex: 'job_title',
        key: 'job_title',
        render: (text) => <a className="text-blue-800 font-bold">{text}</a>,
    }, {
        align: 'center',
        title: '急招程度',
        dataIndex: 'popularity_rating',
        key: 'popularity_rating',
        render: (num) => <Rate allowHalf={true} disabled defaultValue={Number(num)}/>
    }, {
        align: 'center',
        title: '岗位要求',
        width: 250,
        dataIndex: 'job_requirements',
        key: 'job_requirements',
        render: (text) => (
            <Tooltip title={text}>
                <span>{text.length > 20 ? `${text.substring(0, 20)}...` : text}</span>
            </Tooltip>
        )
    }, {
        align: 'center',
        title: '岗位描述',
        width: 250,
        dataIndex: 'job_description',
        key: 'job_description',
        render: (text) => (
            <Tooltip title={text}>
                <span>{text.length > 20 ? `${text.substring(0, 20)}...` : text}</span>
            </Tooltip>
        )
    }, {
        align: 'center',
        width: 100,
        title: '状态',
        dataIndex: 'work_status',
        key: 'work_status',
        render: (status) => {
            const {color, text} = getStatusTag(status);
            return <Tag color={color}>{text}</Tag>;
        },
    }, {
        align: 'center', width: 160,
        title: '薪资待遇', dataIndex: 'salary', key: 'salary'
    }, {
        align: 'center', width: 250,
        title: '福利待遇', dataIndex: 'benefits', key: 'benefits'
    },
        //     {
        //     align: 'center',
        //     title: '远程办公', dataIndex: 'remote', key: 'remote', render: (remote) => remote ? '是' : '否'
        // }, {
        //     align: 'center',
        //     title: '工作期限', dataIndex: 'duration', key: 'duration'
        // },
        {
            align: 'center',
            width: dynamicWidth,
            fixed: 'right',
            title: '操作',
            key: 'action',
            //admin账号的话，以下操作都可以点击
            render: (_, record) => (<div className="flex">
                {
                    record.work_status === 0 && (Role === 1 || Role === 2) && (record.user_id === userInfo.id) ?
                        (<Popconfirm
                            title={<h3>审核确认</h3>}
                            description={
                                <Flex className="my-5 min-w-[300px]" align="center">
                                    <Radio.Group className="mx-auto" options={[{
                                        label: '审核未通过',
                                        value: 2,
                                    },
                                        {
                                            label: '审核通过',
                                            value: 1,
                                        }]} onChange={selectConfirmStatus} value={confirmStatus} optionType="button"
                                                 buttonStyle="solid"/>
                                </Flex>
                            }
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => confirmWork(record.id)}
                        >
                            <Button className="bg-purple-400 text-amber-50" size="small" style={{marginRight: 16}}>
                                审核
                            </Button>
                        </Popconfirm>) : ''
                }
                {
                    record.work_status === 1 && (Role === 1 || Role === 2) && (record.user_id === userInfo.id) ?
                        (
                            <Popconfirm
                                title={`确定下架 ${record.job_title} 岗位吗?`}
                                okText="确定"
                                cancelText="取消"
                                onConfirm={() => handleRemoveWork(record.id)}
                            >
                                <Button size="small" type="primary" danger style={{marginRight: 16}}>下架岗位</Button>
                            </Popconfirm>
                        ) : ''
                }
                <Button size="small" onClick={() => showWorkDetails(record)} style={{marginRight: 16}}>
                    岗位详情
                </Button>
                {
                    Role === 1 || Role === 2 ?
                        (<Button size="small" type="primary" onClick={() => showWorkSeekerDetail(record)}
                                 style={{marginRight: 16}}>
                            查看入职人员
                        </Button>) : ''
                }
                {
                    Role === 3 && record.work_status === 1 && (
                        record.status === 0 ? (
                            <Popconfirm
                                title={`确定应聘 ${record.job_title} 岗位吗?`}
                                okText="确定"
                                cancelText="取消"
                                onConfirm={() => applyWork(record)}
                            >
                                <Button className="bg-teal-500 text-amber-50" size="small" style={{marginRight: 16}}>
                                    应聘
                                </Button>
                            </Popconfirm>
                        ) : record.status === 1 ? (
                            <Button className="bg-amber-600 text-amber-50" size="small" style={{marginRight: 16}} onClick={() => {
                                contactToHr(record)
                            }}>
                                待回复
                            </Button>
                        ) : record.status === 2 ? (
                            <Tag color="volcano" className="text-white cursor-pointer" style={{marginRight: 16}}>
                                不合适
                            </Tag>
                        ) : record.status === 3 ? (
                            <Tag className="text-white bg-blue-400 cursor-pointer" style={{marginRight: 16}}
                                 onClick={() => {
                                     contactToHr(record)
                                 }}>
                                去联系
                            </Tag>
                        ) : record.status === 4 ? (
                            <>
                                {/*<Tag color="blue" className="text-white cursor-pointer" style={{marginRight: 8}}>*/}
                                {/*    待面试*/}
                                {/*</Tag>*/}
                                <Popconfirm
                                    title={`此操作不可逆，确定取消面试吗?`}
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={() => cancelInterview(record, 5)}>
                                    <Button type="primary" danger size="small">
                                        取消面试
                                    </Button>
                                </Popconfirm>
                            </>
                        ) : record.status === 5 ? (
                            <Tag color="orange" className="text-white cursor-pointer" style={{marginRight: 16}}>
                                已放弃面试
                            </Tag>
                        ) : record.status === 6 ? (
                            <Tag color="red" className="text-white cursor-pointer" style={{marginRight: 16}}>
                                面试失败
                            </Tag>
                        ) : record.status === 7 ? (
                            <>
                                <Tag className="text-white bg-blue-400 cursor-pointer" style={{marginRight: 16}}
                                     onClick={() => {
                                         contactToHr(record)
                                     }}>
                                    去联系
                                </Tag>
                                <Popconfirm
                                    title={`确定入职吗?`}
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={() => acceptOffer(record)}>
                                    <Button className="bg-green-500 text-white" size="small"
                                            style={{marginRight: 8}}>
                                        接受入职
                                    </Button>
                                </Popconfirm>
                                <Popconfirm
                                    title={`确定放弃入职吗?`}
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={() => cancelInterview(record, 9)}>
                                    <Button className="bg-red-500 text-white" size="small">
                                        放弃入职
                                    </Button>
                                </Popconfirm>
                            </>
                        ) : record.status === 8 ? (
                            <Tag color="green" className="text-white cursor-pointer" style={{marginRight: 16}}>
                                已入职
                            </Tag>
                        ) : record.status === 9 ? (
                            <Tag color="black" className="text-white cursor-pointer" style={{marginRight: 16}}>
                                放弃入职
                            </Tag>
                        ) : null
                    )
                }

                {
                    (Role === 1 || Role === 2) && record.user_id === userInfo.id ?
                        (
                            <Popconfirm
                                title={`确定删除 ${record.job_title} 岗位吗?`}
                                okText="确定"
                                cancelText="取消"
                                onConfirm={() => handleDeleteWork(record.id)}
                            >
                                <Button size="small" type="primary" danger>删除</Button>
                            </Popconfirm>
                        ) : ''
                }

            </div>),
        }]

    const getDataList = () => {
        // const params = new URLSearchParams({
        //     IsPerson:queryIsPerson
        // }).toString();
        http.get(`/work/getWorkDataList?${queryIsPerson}`).then((res) => {
            setWorkList(res.data)
        }).catch((error) => {
            logout();
            message.error(error)
        })
    }

    const logout = () => {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        router.push('/login');
    }

    const getStatusTag = (status) => {
        const statusMap = {
            0: {color: 'blue', text: '待审核'},
            1: {color: 'green', text: '审核通过'},
            2: {color: 'red', text: '审核未通过'},
            3: {color: 'orange', text: '已下架'}
        };
        return statusMap[status] || {color: 'default', text: '未知状态'};
    };

    //搜索框自定义薪资输入框
    const [queryConfirm, setQueryConfirm] = useState(null);
    const [minSalary, setMinSalary] = useState(null);
    const [maxSalary, setMaxSalary] = useState(null);
    const [salaryUnit, setSalaryUnit] = useState(null);
    const [querySalary, setQuerySalary] = useState(null);
    const [queryWorkInput, setQueryWorkInput] = useState(null)
    const [salaryOpen, setSalaryOpen] = useState(false);
    const SalaryQueryChange = value => {
        setQuerySalary(value)
        const parts = value.split('/');
        if (parts.length > 1) {
            const range = parts[0].split('-');
            const unit = parts[1].trim();
            setMinSalary(Number(range[0].trim()))
            setMaxSalary(Number(range[1].trim()))
            setSalaryUnit(unit)
        }
    }

    //处理salary
    const formatSalry = () => {
        const querySal = minSalary + '-' + maxSalary + '/' + '月'
        setQuerySalary(querySal)
        setSalaryOpen(false)
    }
    const [queryIsPerson, setQueryIsPerson] = useState(2)

    //查询筛选条件的数据
    const searchQuery = () => {
        const params = new URLSearchParams({
            IsPerson: queryIsPerson,
            queryConfirm: queryConfirm,
            minSalary: minSalary,
            maxSalary: maxSalary,
            salaryUnit: salaryUnit,
            queryWorkInput: queryWorkInput
        }).toString();
        http.get(`/work/getWorkDataList?${params}`).then((res) => {
            setWorkList(res.data)
        }).catch((error) => {
            logout();
            message.error(error)
        })
    }

    //重置
    const resetQuery = () => {
        setQueryConfirm(null)
        setMinSalary(null)
        setMaxSalary(null)
        setSalaryUnit(null)
        setQuerySalary(null)
        setQueryWorkInput(null)
        getDataList();
    }

    //过滤所有或个人数据
    const changeQueryIsPersonData = (e) => {
        console.log(e.target.value)
        setQueryIsPerson(e.target.value)
        const params = new URLSearchParams({
            IsPerson: queryIsPerson,
            queryConfirm: queryConfirm,
            minSalary: minSalary,
            maxSalary: maxSalary,
            salaryUnit: salaryUnit,
            queryWorkInput: queryWorkInput
        }).toString();
        http.get(`/work/getWorkDataList?${params}`).then((res) => {
            setWorkList(res.data)
        }).catch((error) => {
            logout();
            message.error(error)
        })
    }

    useEffect(() => {
        http.get('/work/getWorkCount').then((res) => {
            console.log('1231231', res)
            setWorkCounts(res.data)
        })
        const user = (JSON.parse(localStorage.getItem('userInfo')))
        setUserInfo(user)
        getDataList();
        setRole(user.role)
    }, [])


    return (
        <div className="p-8 bg-gray-100">
            <Flex>
                <Flex vertical className="min-w-[1000px]">
                    <h1 className="text-2xl font-bold text-center mb-6">岗位统计表</h1>
                    <div className="grid grid-cols-4 gap-4">
                        <div
                            className="transform hover:scale-105 transition-transform duration-300 bg-white shadow-lg hover:shadow-xl rounded-xl p-6 flex flex-col items-center justify-center cursor-pointer">
                            <p className="text-lg font-semibold">岗位数量</p>
                            <p className="text-3xl font-bold text-blue-500">{workCounts.totalJobs}</p>
                        </div>
                        <div
                            className="transform hover:scale-105 transition-transform duration-300 bg-white shadow-lg hover:shadow-xl rounded-xl p-6 flex flex-col items-center justify-center cursor-pointer">
                            <p className="text-lg font-semibold">应聘人数</p>
                            <p className="text-3xl font-bold text-green-500">{workCounts.totalApplicants}</p>
                        </div>
                        <div
                            className="transform hover:scale-105 transition-transform duration-300 bg-white shadow-lg hover:shadow-xl rounded-xl p-6 flex flex-col items-center justify-center cursor-pointer">
                            <p className="text-lg font-semibold">在职人数</p>
                            <p className="text-3xl font-bold text-red-500">12</p>
                        </div>
                        <div
                            className="transform hover:scale-105 transition-transform duration-300 bg-white shadow-lg hover:shadow-xl rounded-xl p-6 flex flex-col items-center justify-center cursor-pointer">
                            <p className="text-lg font-semibold">岗位平均薪资</p>
                            <p className="text-3xl font-bold text-amber-600">{workCounts.averageSalary}</p>
                        </div>
                    </div>
                </Flex>
                <Flex className="ml-10 flex flex-col w-full lg:max-w-md space-y-4">
                    <Select
                        className="w-full"
                        value={queryConfirm}
                        onChange={setQueryConfirm}
                        placeholder="请选择审核状态"
                        options={[
                            {
                                value: 0,
                                label: '待审核',
                            },
                            {
                                value: 1,
                                label: '审核通过',
                            },
                            {
                                value: 2,
                                label: '审核未通过',
                            },
                            {
                                value: 3,
                                label: '已下架',
                            },
                        ]}
                    />

                    <Select
                        className="w-full"
                        placeholder="请选择薪资待遇或自定义薪资"
                        onChange={SalaryQueryChange}
                        value={querySalary}
                        open={salaryOpen}
                        onDropdownVisibleChange={(visible) => setSalaryOpen(visible)}
                        dropdownRender={(menu) => (
                            <>
                                {menu}
                                <Divider
                                    style={{
                                        margin: '8px 0',
                                        width: '440px'
                                    }}
                                />
                                <Space
                                    style={{
                                        padding: '0 8px 4px',
                                    }}
                                >
                                    <InputNumber
                                        min={1} max={10000000} value={minSalary}
                                        onChange={setMinSalary}
                                        style={{
                                            width: '150px',
                                        }}
                                        placeholder="请输入最低薪资"
                                    />
                                    <span className="font-bold">
                                                -
                                            </span>
                                    <InputNumber
                                        min={1} max={10000000} value={maxSalary}
                                        onChange={setMaxSalary}
                                        style={{
                                            width: '150px',
                                        }}
                                        placeholder="请输入最高薪资"
                                    />
                                    <Button type="text" icon={<PlusOutlined/>} onClick={formatSalry}>
                                        确认
                                    </Button>
                                </Space>
                            </>
                        )}
                    >
                        <Option value="4000-5000/月">4000-5000/月</Option>
                        <Option value="5000-6000/月">5000-6000/月</Option>
                        <Option value="6000-7000/月">6000-7000/月</Option>
                        <Option value="7000-8000/月">7000-8000/月</Option>
                        <Option value="8000-10000/月">8000-10000/月</Option>
                        <Option value="10000-12000/月">10000-12000/月</Option>
                    </Select>
                    <Input placeholder="请输入岗位名称关键词" className="w-full" value={queryWorkInput}
                           onChange={(e) => setQueryWorkInput(e.target.value)}/>
                    <div className="flex flex-row justify-between">
                                <Radio.Group onChange={changeQueryIsPersonData} value={queryIsPerson}>
                                    <Radio value={2}>所有岗位</Radio>
                                    {
                                        Role===1 ? (<Radio value={1}>个人发布</Radio>):''
                                    }
                                </Radio.Group>
                        <div>

                        </div>
                        <div>
                            <Button onClick={resetQuery}
                                    className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mr-4">
                                重置
                            </Button>
                            <Button onClick={searchQuery}
                                    className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                                搜索
                            </Button>
                        </div>
                    </div>
                </Flex>
            </Flex>

            <div className="mt-4">
                <Table
                    scroll={{
                        x: 1750,
                    }}
                    pagination={{
                        pageSize: 8
                    }}
                    columns={columns}
                    dataSource={workList}
                    bordered
                    title={() => <TableTitle onAddClick={handleAddClick}/>}
                    rowKey="id"
                />
            </div>
            <Modal
                width={600}
                title="发布岗位"
                visible={publishModalVisible}
                onOk={() => {
                    publishWork()
                }}
                onCancel={() => {
                    setPublishModalVisible(false)
                    workForm.resetFields();
                }}
                okText="创建"
                cancelText="取消"
            >
                <Form
                    layout="inline"
                    form={workForm}
                    name="workForm"
                >
                    <Flex gap="middle">
                        <Form.Item
                            label="岗位名称"
                            name="job_title"
                            rules={[{required: true, message: '请输入岗位名称!'}]}
                        >
                            <Input placeholder="请输入岗位名称"/>
                        </Form.Item>
                        <Form.Item
                            label="急招程度"
                            name="popularity_rating"
                        >
                            <Rate allowHalf defaultValue={1}/>
                        </Form.Item>
                    </Flex>
                    <Form.Item
                        className="mt-6"
                        label="岗位要求"
                        name="job_requirements"
                        rules={[{required: true, message: '请输入岗位要求!'}]}
                    >
                        <TextArea
                            showCount
                            maxLength={100}
                            placeholder="请输入岗位要求"
                            style={{
                                height: 80,
                                width: 415,
                                resize: 'none',
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        className="mt-6"
                        label="岗位描述"
                        name="job_description"
                        rules={[{required: true, message: '请输入岗位描述!'}]}
                    >
                        <TextArea
                            showCount
                            maxLength={100}
                            placeholder="请输入岗位描述"
                            style={{
                                height: 80,
                                width: 415,
                                resize: 'none',
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        className="mt-8"
                        name="salary"
                        label="薪资待遇"
                        rules={[{required: true, message: '请选择或输入薪资待遇!'}]}
                    >
                        <Select
                            className="min-w-[415px]"
                            placeholder="请选择薪资待遇或自定义薪资"
                            onChange={handleSalaryChange}
                        >
                            <Option value="4000-5000/月">4000-5000/月</Option>
                            <Option value="5000-6000/月">5000-6000/月</Option>
                            <Option value="6000-7000/月">6000-7000/月</Option>
                            <Option value="7000-8000/月">7000-8000/月</Option>
                            <Option value="8000-10000/月">8000-10000/月</Option>
                            <Option value="10000-12000/月">10000-12000/月</Option>
                            <Option value="custom">自定义薪资</Option>
                        </Select>
                    </Form.Item>
                    {customInput && (
                        <Form.Item className="mt-4">
                            <Flex>
                                <Input.Group compact>
                                    <Form.Item
                                        name="min_salary"
                                        noStyle
                                        rules={[{required: true, message: '请输入最低薪资'}]}
                                    >
                                        <InputNumber style={{width: '50%'}} min={0} max={100000}
                                                     placeholder="最低薪资"/>
                                    </Form.Item>
                                    <Form.Item
                                        name="max_salary"
                                        noStyle
                                        rules={[{required: true, message: '请输入最高薪资'}]}
                                    >
                                        <InputNumber style={{width: '50%'}} min={1} max={100000}
                                                     placeholder="最高薪资"/>
                                    </Form.Item>
                                </Input.Group>
                                <Form.Item
                                    className="ml-8"
                                    name="salary_unit"
                                    rules={[{required: true, message: '请选择薪资单位'}]}
                                >
                                    <Select placeholder="选择单位">
                                        <Option value="小时">小时</Option>
                                        <Option value="天">天</Option>
                                        <Option value="月">月</Option>
                                        <Option value="年">年</Option>
                                    </Select>
                                </Form.Item>
                            </Flex>
                        </Form.Item>
                    )}
                    <Form.Item
                        className="mt-6"
                        name="benefits"
                        label="福利待遇"
                        rules={[{required: true, message: '请选择福利待遇!'}]}
                    >
                        <Select
                            onChange={benefitChange}
                            allowClear
                            className="min-w-[415px]"
                            mode="multiple"
                            placeholder="选择福利待遇"
                        >
                            {benefitOptions.map(option => (
                                <Option key={option.value} value={option.value}>
                                    {option.label}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        className="mt-6"
                        name="remote"
                        label="是否远程办公"
                        rules={[{required: true, message: '请选择是否远程办公!'}]}
                    >
                        <Select
                            placeholder="选择是否远程办公"
                        >
                            <Option value={1}>是</Option>
                            <Option value={0}>否</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        className="mt-6 ml-3"
                        name="duration"
                        label="工作期限"
                        rules={[{required: true, message: '请选择工作期限!'}]}
                    >
                        <Select
                            placeholder="选择工作期限"
                        >
                            <Option value="长期">长期</Option>
                            <Option value="短期">短期</Option>
                            <Option value="外包">外包</Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
            <WorkDetail
                visible={workDetailVisible}
                onClose={closeWorkDetail}
                workData={workDetailData}
            />
            <Modal
                title="入职人员详情"
                visible={seekersDetailVisible}
                onCancel={closeWorkSeekerDetail}
                footer={null}
                width={1100}
            >
                <List itemLayout="horizontal" dataSource={seekersDetailData}
                      renderItem={(item, index) => (
                          <List.Item actions={renderActions(item)}>
                              <List.Item.Meta
                                  avatar={<Avatar src={item.avatar}/>}
                                  title={<a>{item.nickname}</a>}
                                  description={item.work_position}
                              />
                          </List.Item>
                      )}>
                </List>
            </Modal>
            <Modal
                title="应聘人详情"
                visible={seekerOneDetail}
                onCancel={closeSeekerOneDetail}
                footer={
                    <Button onClick={() => setSeekerOneDetail(false)}>
                        关闭
                    </Button>
                }
                width={1100}>
                <Descriptions bordered items={SeekerOneDetailItems} column={2}/>
            </Modal>
        </div>

    );
}
